from django.shortcuts import render

# Create your views here.

from django.views import View
from users.models import User
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.contrib.auth import login
from .models import User
import json,re

class UsernameCountView(View):

    def get(self,request,username):
        # 判断用户名是否存在
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({
                'code':404,
                'errmsg':"查询数据库失败！！！"
            })
        return JsonResponse(
            {
                'code':0,
                'errmsg':'ok',
                'count':count

            }
        )

class MobliesConntView(View):
    def get(self,request,mobile):
        # 判断手机号是否存在
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e :
            return JsonResponse({
                'code':404,
                'errmsg':"查询数据库失败！！！"
            })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'count':count
        })


class RegisterView(View):
    '''
     验证用户注册
    '''

    def post(self,request):
    # 1.接收请求参数，并对请求参数进行校验
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        allow = data.get('allow')
    # 1.1 必传参数校验
        if not all([username,password,password2,mobile,sms_code,allow]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数！！！'
            })
    # 1.2 对用户名进行校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return JsonResponse({
                'code':400,
                'errmsg':'用户名格式错误！'
            })
    # 1.3 对密码进行校验
        if not re.match(r'^[a-zA-Z0-9_]{8,20}$',password):
            return JsonResponse({
                'code':400,
                'errmsg':'密码格式错误！！！'
            })
        if password != password2:
            return JsonResponse({
                'code':400,
                'errmsg':'两次输入的密码不一致！'
            })
    # 1.4 对手机号进行校验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({
                'code':400,
                'errmsg':'手机号格式有误！！！'
            })
    # 1.5 对短信验证码进行验证
        if not re.match(r'\d{6}',sms_code):
            return JsonResponse({
                'code':400,
                'errmsg':'手机验证码格式有误！！！'
            })
    # 1.6 对allow字段进行校验
    # isinstance()  :判断是否是bool类型数据
        if not isinstance(allow,bool):
            return JsonResponse({
                'code':400,
                'errmsg':'allow字段有误！'
            })
        if  allow != True:
            return JsonResponse({
                'code':400,
                'errmsg':'请先同意用户协议！！！'
            })
    # 1.7 对短信验证码进行比对
        # 连接数据库
        conn = get_redis_connection('verify_code')
        # 从数据库中获取短信验证码
        sms_code_from_redis = conn.get('sms_%s'%mobile)
        # 判断验证码是否已经过期
        if not sms_code_from_redis:
            return JsonResponse({
                'code':400,
                'errmsg':'短信验证码已经过期！！'
            })
        if sms_code_from_redis.decode() != sms_code :
            return JsonResponse({
                'code':400,
                'errmsg':'短信验证码错误！！！'
            })

    # 2. 创建用户模型类对象，把数据存到redis数据库中

        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile
                                            )
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'打开数据库失败！！！'
            })
    # 3. 设置session,记录用户登录信息
        # 旧方法
        # request.session['username']=user.username

        # login()  帮我们把用户数据写入到session缓存中
        login(request,user)

    # 4.构建响应信息返回
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        # 通过响应对象设置cookie信息
        response.set_cookie('username',user.username)
        return response


from django.contrib.auth import authenticate
class LoginView(View):
    '''
    用户登录函数
    '''

    def post(self,request):
        # 1 获取参数
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        # 1.1 检验必传参数
        if not all([username,password]):
            return JsonResponse({
                'code':400,
                'errmsg':'必传参数有误！'
            })
        # 1,2 用户名比对
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return JsonResponse({
                'code':400,
                'errmsg':'用户名格式错误！'
            })

        # 1.3 密码校验
        if not re.match(r'^[a-zA-Z0-9_]{8,20}$', password):
            return JsonResponse({
                'code': 400,
                'errmsg': '密码格式有误！'
            })

        # 1.4 校验remembered字段
        if not isinstance(remembered, bool):
            return JsonResponse({
                'code': 400,
                'errmsg': "remembered参数有误！"
            })

        # 2. 判断用户名和密码
        # 传统方式
        # try:
        #     user = User.objects.get(username=username)
        # except User.DoesNotExist as e:
        # #     return JsonResponse({
        #         'code':400,
        #         'errmsg':'用户不存在！！！'
        #     })
        # if not user.check_password(password):
        #     return JsonResponse({
        #         'code':400,
        #         'errmsg':'密码有外遇！'
        #     })
        # 新方法: authenticate()  校验成功返回用户对象，校验失败返回None
        user = authenticate(request,username=username,password=password)
        if not user:
            return JsonResponse({
                'code':400,
                'errmsg':'用户名或者密码错误！'
            })
        # 3.判断是否要记住用户名
        login(request,user)
        if remembered:
            # session 默认会保存两周
            # set_expiry()  设置session保存的时间， None表示遵循session默认的保存时间
            request.session.set_expiry(None)
        else:
            # set_expiry(0) 表示浏览器关闭后，马上清除session信息，删除redis库中记录的用户记录
            request.session.set_expiry(0)
        # 构建响应返回
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        # 设置session，保持用户数据
        response.set_cookie('username',user.username)
        return response

from django.contrib.auth import logout
class LogoutView(View):
    '''
    用户退出函数
    '''
    def delete(self,request):

        # 1. 清除用户登录数据
        # logout():先通过request.COOKIES() 获取sessionid, 再根据sessionid找到缓存的数据，最后删除session数据
        logout(request)

        # 2. 清楚cookie信息
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        response.delete_cookie('username')
        return response


# class UserInfoView(View):
    '''
    返回用户首页函数
    '''

    # 1.验证用户是否登录
    # 方案一：根据request.user来判断

    # 先获取从session认证出来的对象：request.user
    # request.user是由中间件：'django.contrib.auth.middleware.AuthenticationMiddleware',来赋值的
    # 再根据这个对象来判断用户是否已经登录

    # request.user 是一个根据session数据，验证出来的对象，如果没有session则返回的是一个匿名用户对象
    # request.user.is_authenticated  用来判断用户是否存在，存在返回的是True
    # request.user.is_anonymous  用来判断用户师范是匿名用户，如果是则，返回的是True


    # 2.构建响应，返回用户数据

    # def get(self,request):
    #     if not request.user.is_authenticated:
    #         return JsonResponse({
    #             'code':400,
    #             'errmsg':'用户未登录！'
    #         })
    #     return JsonResponse({
    #         'code':0,
    #         'errmsg':'ok',
    #         'info_data':{
    #             'username':request.user.username,
    #             'mobile':request.user.mobile,
    #             'email':request.user.email
    #         }
    #     })



    # 方案二：使用自定义装饰器来判断用户是否登录   --->把装饰函数封装在一个模块中

    from django.utils.decorators import method_decorator
    from meiduo_mall.utils.view import log_register
    # @method_decorator(log_register)
    # def get(self,request):
    #
    #     return JsonResponse({
    #         'code':0,
    #         'errmsg':'ok',
    #         'info_data':{
    #             'username':request.user.username,
    #             'mobile':request.user.mobile,
    #             'email':request.user.email
    #         }
    #     })
    # 方案三：通过自定义拓展类来实现登录装饰，既判断用户是否已经登录
from meiduo_mall.utils.view import LoginRequiredMixin
class UserInfoView(LoginRequiredMixin, View):

    def get(self, request):
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email
            }
        })


class EmailView(View):
    '''
    添加邮箱
    '''
    def put(self,request):
        # 1.获取请求参数：email
        data = json.loads(request.body.decode())
        email = data.get('email')

        # 2.校验参数
        if not email:
            return JsonResponse({
                'code':400,
                'errmsg':'缺少参数!'
            })
        if not re.match(r'^^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$$',email):
            return JsonResponse({
                'code':400,
                'errmsg':'邮箱格式错误！'
            })
        # 3.更改用户邮箱信息
        # 通过用户对象request.user 来更改邮箱信息
        try:
            request.user.email=email
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'数据库访问失败！'
            })
        # 4.构建响应返回
        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
from users.models import Address
from meiduo_mall.utils.view import LoginRequiredMixin
class CreateAddressView(LoginRequiredMixin,View):
    '''
    新增地址函数
    '''
    def post(self,request):
        # 地址对多设置20个
        # 1.获取用户地址个数，并判断是否符合要求
        try:
            count = Address.objects.filter(user=request.user,is_deleted=False).count()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '数据库打开失败！'
            })
            # 2. 获
        if count > 20:
            return JsonResponse({
                'code':400,
                'errmsg':'地址个数超出限制！'
            })
    # 1.获取前段传过来的参数

        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 3. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数！'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})
        # 4.创建Address模型类对象，并把数据保存到数据库中

        # 根据用户来保存地址信息
        data['user'] = request.user
        # data = {"receiver": '韦小宝'} --> create(**data) --> create(receiver='韦小宝')
        try:
            address = Address.objects.create(**data)
            # 如果该用户没有设置默认地址，那么在新建地址的时候，把该地址设置为默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'新增地址失败！'
            })
        # 5.构建响应返回
        address_dict = {
            'id':address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
            }
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'address':address_dict
        })
#
class AddressView(LoginRequiredMixin,View):
    '''
    用户收货地址给前端展示
    '''
    def get(self,request):
        # 1.获取该用户的所用地址
        user_address = Address.objects.filter(user=request.user,is_deleted=False)
        # 2.构建响应返回
        address_list = []
        for address in user_address:
            # 如果当前地址是用户的默认地址，则把改地址追加到列表头部

            if address.id == request.user.default_address_id:
                address_list.insert(0, {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                })
            else:
                # address模型类对象
                address_list.append({
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                })

        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'default_address_id': request.user.default_address_id,
            'addresses':address_list,

        })

class UpdateDestroyAddressView(View):
    '''
    用户修改地址函数
    用户删除地址函数
    '''
    def put(self,request,address_id):
        # 1. 获取请求参数
        data = json.loads(request.body.decode())
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        # 2. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数！'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})
        # 3. 根据address_id更改用户地址信息
                # data = {"province": "芜湖市", "province_id": 34}
                # update(province=<对象>),更新或者新建模型类对象的外键字段必须赋值成关联对象
                # 而前端传来的是字符串；另外，我们是根据关联的主键id新建/更新的；
        try:
            data.pop('province')
            data.pop('city')
            data.pop('district')
            Address.objects.filter(pk=address_id).update(**data)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'更新地址失败！'
            })

        # 4. 构建响应返回
        address = Address.objects.get(pk=address_id)
        return JsonResponse({
            'code':0,
            'errmsg':'更新地址成功！',
            'address':{
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

        })
    # 用户删除地址函数
    def delete(self,request,address_id):
        # 1. 根据address_id 获取用户地址信息
        try:
            address = Address.objects.get(pk=address_id)
            # 2. 删除地址---->只是逻辑删除
            address.is_deleted=True
            address.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'删除失败！'
            })
        # 3. 构建响应返回
        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })

class DefaultAddressView(View):
    '''
    设置默认地址
    '''
    def put(self,request,address_id):
        # 1. 根据address_id 获取用户地址
        try:
            address = Address.objects.get(pk=address_id)
            # 2. 修改把该地址设置为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'设置失败！'
            })
        # 3. 构建响应返回
        return JsonResponse({
            'code':0,
            'errmsg':'设置成功！'
        })

class  UpdateTitleAddressView(View):
    '''
    修改地址标题
    '''
    def put(self,request,address_id):
        # 1. 获取请求参数：title
        data = json.loads(request.body.decode())
        title = data.get('title')
        # 2. 根据address_id获取用户地址
        try:
            address = Address.objects.get(pk=address_id)
            # 3. 修改用户地址标题
            address.title = title
            address.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'更改标题失败！'
            })
        # 4. 构建响应返回
        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })

class ChangePasswordView(LoginRequiredMixin, View):
    '''
    修改用户密码
    '''
    def put(self,request):
        # 1. 获取参数：old_password,new_password,new_password2
        data = json.loads(request.body.decode())
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')
        # 2.校验参数
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({
                'code':400,
                'errmsg':'参数有误！'
            })
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传字段！'})

        if new_password2 != new_password:
            return JsonResponse({'code': 400, 'errmsg': '两次数据不一致！'})

            # 判断旧密码是否正确
        user = request.user
        if not user.check_password(raw_password=old_password):  # 传入明文密码
            return JsonResponse({'code': 400, 'errmsg': '密码输入错误！'})
        # 3.修改密码
        user.set_password(new_password)
        user.save()
        # 4.构建响应返回
        return JsonResponse({'code': 0, 'errmsg': 'ok'})